/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.CC;

import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import merlion.common.entity.SecurityRole;
import merlion.common.entity.Staff;
import merlion.common.util.Consts;
import merlion.frm.ccm.entity.CreditGroup;
import merlion.frm.ccm.session.CCSessionBeanLocal;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Zhiqi
 */
@ManagedBean(name = "cgManagerBean")
@ViewScoped
public class CreditGroupManagerBean {

    @EJB
    private CCSessionBeanLocal ccSessionBean;
    private CreditGroup cg;
    private Collection<CreditGroup> cgs;
    private Staff loginUser;
    private String statusMsg;
    private CreditGroup prevDs;
    private CreditGroup nextDs;
    private CreditGroup prevWs;
    private CreditGroup nextWs;

    //--------------------------------------------------------------------------
    //                             Constructor
    //--------------------------------------------------------------------------
    public CreditGroupManagerBean() {
        cg = new CreditGroup();
        loginUser = (Staff) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("app.user.name");
        statusMsg = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("statusMsg");
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("statusMsg");

        if (statusMsg != null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMsg, ""));
        }
    }

    @PostConstruct
    public void init() {
    }

    //--------------------------------------------------------------------------
    //                     Credit Group Manager Bean
    //--------------------------------------------------------------------------
    public Collection<CreditGroup> getAllCreditGroup() {
        cgs = ccSessionBean.getAllCreditGroup();
        return cgs;
    }

    public String updateCreditGroupDS() {
        return "manageCreditGroupEditDS?faces-redirect=true";
    }

    public String updateCreditGroupWS() {
        return "manageCreditGroupEditWS?faces-redirect=true";
    }

    public boolean isFinanceVP() {
        for (SecurityRole sr : loginUser.getSecurityRoles()) {
            if (sr.getRoleName().equals(Consts.FIN_VP_ROLE)) {
                return true;
            }
        }
        return false;
    }

    public void updateCreditGroup(ActionEvent event) {
        cg = (CreditGroup) event.getComponent().getAttributes().get("selectedCreditGroup");

        prevDs = ccSessionBean.getPreviousCreditGroupDs(cg);
        nextDs = ccSessionBean.getNextCreditGroupDs(cg);
        prevWs = ccSessionBean.getPreviousCreditGroupWs(cg);
        nextWs = ccSessionBean.getNextCreditGroupWs(cg);
    }

    public void setRemoveCreditGroup(ActionEvent event) {
        cg = (CreditGroup) event.getComponent().getAttributes().get("selectedCreditGroup");
    }

    public void removeCreditGroup(ActionEvent event) {

        System.out.println("Credit Group: " + cg.getId());

        //TODO: Remove
        boolean success = ccSessionBean.removeCreditGroupById(cg.getId());
        if (success) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Credit Group " + cg.getCreditGroupTitle() + " removed successfully.", ""));
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group " + cg.getCreditGroupTitle() + " cannot be removed. Credit Group is still linked to credit account.", ""));
        }
    }

    public String saveMainCreditGroup() {

        RequestContext context = RequestContext.getCurrentInstance();

        //Validate
        boolean valid = true;
        if (cg.getExtensionDays() == null || cg.getExtensionDays() == 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Extension days cannot be zero", ""));
            valid = false;
        }
        if (cg.getCreditGroupTitle().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group Title cannot be empty", ""));
            valid = false;
        }
        context.addCallbackParam("valid", valid);

        if (valid) {
            cg = ccSessionBean.createCreditGroup(cg);

            if (cg != null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Credit Group " + cg.getCreditGroupTitle() + " updated successfully.", ""));
                statusMsg = "Credit Group " + cg.getCreditGroupTitle() + " updated successfully.";
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", statusMsg);
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group update has failed. Credit Group Title may have existed. Please try again.", ""));
                statusMsg = "Credit Group update has failed. Credit Group Title may have existed. Please try again.";
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", statusMsg);
            }
        }

        return null;
    }

    public String saveCreditGroup() {

        RequestContext context = RequestContext.getCurrentInstance();

        //Validate
        boolean valid = true;

        if (prevDs != null) {
            if (cg.getUpgradeLimitForDs() <= prevDs.getUpgradeLimitForDs()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upgrade Limit is invalid. Upgrade limit must be between " + prevDs.getUpgradeLimitForDs() + " to " + nextDs.getUpgradeLimitForDs() + ".", ""));
                valid = false;
            }
        }
        if (nextDs != null) {
            if (cg.getUpgradeLimitForDs() >= nextDs.getUpgradeLimitForDs()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upgrade Limit is invalid. Upgrade limit must be between " + prevDs.getUpgradeLimitForDs() + " to " + nextDs.getUpgradeLimitForDs() + ".", ""));
                valid = false;
            }
        }
        if (prevDs != null) {
            if (cg.getUpgradeLimitForWs() <= prevWs.getUpgradeLimitForWs()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upgrade Limit is invalid. Upgrade limit must be between " + prevDs.getUpgradeLimitForWs() + " to " + nextDs.getUpgradeLimitForWs() + ".", ""));
                valid = false;
            }
        }
        if (nextWs != null) {
            if (cg.getUpgradeLimitForWs() >= nextWs.getUpgradeLimitForWs()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upgrade Limit is invalid. Upgrade limit must be between " + prevDs.getUpgradeLimitForWs() + " to " + nextDs.getUpgradeLimitForWs() + ".", ""));
                valid = false;
            }
        }


        context.addCallbackParam("valid", valid);

        if (valid) {
            cg = ccSessionBean.updateCreditGroup(cg);

            if (cg != null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Credit Group " + cg.getCreditGroupTitle() + " updated successfully.", ""));
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group update has failed. Credit Group Title may have existed. Please try again.", ""));
            }
        }

        return null;
    }

    public String createCreditGroup() {

        //Validate
        boolean valid = true;
        if (cg.getExtensionDays() == null || cg.getExtensionDays() == 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Extension days cannot be zero", ""));
            valid = false;
        }
        if (cg.getCreditGroupTitle().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group Title cannot be empty", ""));
            valid = false;
        }
        if (ccSessionBean.checkExistCreditGroupByTitle(cg.getCreditGroupTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group Title currently exist", ""));
            valid = false;
        }
        //Get previous credit group
        CreditGroup prevDs = ccSessionBean.getPreviousCreditGroupDs(cg);
        CreditGroup nextDs = ccSessionBean.getNextCreditGroupDs(cg);
        //Get next credit group
        CreditGroup prevWs = ccSessionBean.getPreviousCreditGroupWs(cg);
        CreditGroup nextWs = ccSessionBean.getNextCreditGroupWs(cg);

        if (prevDs == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Direct Sales Upgrade Limit is invalid. Upgrade limit must be more than the highest upgrade limit currently", ""));
            valid = false;
        }
        if (prevWs == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Wholesales Upgrade Limit is invalid. Upgrade limit must be more than the highest upgrade limit currently", ""));
            valid = false;
        }
        if (nextDs != null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Direct Sales Upgrade Limit is invalid. Upgrade limit must be more than the highest upgrade limit currently", ""));
            valid = false;
        }
        if (nextWs != null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Wholesales Upgrade Limit is invalid. Upgrade limit must be more than the highest upgrade limit currently", ""));
            valid = false;
        }

        if (valid) {
            cg = ccSessionBean.createCreditGroup(cg);

            if (cg != null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Credit Group " + cg.getCreditGroupTitle() + " created successfully.", ""));
                cg = new CreditGroup();
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Credit Group update has failed. Please try again.", ""));
            }
        }

        return null;
    }

    //--------------------------------------------------------------------------
    //                      Getter and Setter
    //--------------------------------------------------------------------------
    public CreditGroup getCg() {
        return cg;
    }

    public void setCg(CreditGroup cg) {
        this.cg = cg;
    }

    public Collection<CreditGroup> getCgs() {
        return cgs;
    }

    public void setCgs(Collection<CreditGroup> cgs) {
        this.cgs = cgs;
    }

    public Staff getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Staff loginUser) {
        this.loginUser = loginUser;
    }

    public String getStatusMsg() {
        return statusMsg;
    }

    public void setStatusMsg(String statusMsg) {
        this.statusMsg = statusMsg;
    }

    //--------------------------------------------------------------------------
    //                              Validate
    //--------------------------------------------------------------------------
    private boolean isAlphabetic(String str) {
        if (str.matches("[a-zA-Z\\s]*")) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isAlphanumeric(String str) {

        if (str.matches("[a-zA-z0-9\\s]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNumeric(String str) {
        if (str.matches("[0-9]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNotEmpty(String str) {
        if (str == null) {
            return false;
        }
        if (str.equals("")) {
            return false;
        }
        return true;
    }

    private boolean validate(CreditGroup cg) {

        boolean valid = true;
        // Member Discount Group Name: Required, Alphanumeric
        if (!isNotEmpty(cg.getCreditGroupTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Credit Group Name", "cannot be empty."));
            valid = false;
        }
        if (!isAlphanumeric(cg.getCreditGroupTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Credit Group Name", "can only contain alphanumeric characters."));
            valid = false;
        }

        //Credit Limit: Required, not 0
//        if (cg.getCreditLimit() == null) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Credit Limit", "cannot be empty."));
//            valid = false;
//        } 
//        if (cg.getCreditLimit() <= 0) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Credit Limit", "cannot be <= 0."));
//            valid = false;
//            }

        //Extension Date: Required, >0
        if (cg.getExtensionDays() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Extension Date", "cannot be empty."));
            valid = false;
        }
        if (cg.getExtensionDays() <= 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Extension Date", "cannot be <= 0."));
            valid = false;
        }

        //Upgrade Limit: Required, >0
//        if (cg.getUpgradeLimit() == null) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Upgrade Limit", "cannot be empty."));
//            valid = false;
//        } 
//        if (cg.getUpgradeLimit() <= 0) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Upgrade Limit", "cannot be <= 0."));
//            valid = false;
//            }

        return valid;
    }
}
